package com.laizhenghua.wxstub.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.laizhenghua.wxstub.constant.AppConstant;
import com.laizhenghua.wxstub.entiry.LoginUser;
import com.laizhenghua.wxstub.utils.JwtUtil;
import com.laizhenghua.wxstub.utils.R;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @description: 登录拦截器
 * @author: laizhenghua
 * @date: 2022/9/8 21:34
 */
@Component("loginInterceptor")
public class LoginInterceptor extends OncePerRequestFilter {
    private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LoginInterceptor.class);
    private static AntPathMatcher pathMatcher = new AntPathMatcher();
    @Autowired
    private CacheManager cacheManager;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        // token=1用于swagger页面调用API
        if (!StringUtils.hasText(token) || "1".equals(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        log.info("intercept " + request.getRequestURI());
        // 解析token
        Claims claims = null;
        try {
            claims = JwtUtil.parseToken(token);
        } catch (Exception e) {
            log.error(e);
            fallback("token解析失败(非法token)！", response);
            return;
        }
        String _id = claims.getSubject();
        Cache cache = cacheManager.getCache(AppConstant.LOGIN_TOKEN_CACHE_NAME);
        if (cache == null) {
            fallback(null, response);
            return;
        }
        LoginUser loginUser = cache.get(_id, LoginUser.class);
        if (loginUser == null) {
            fallback("token失效，请重新登录！", response);
            return;
        }
        log.info(JSON.toJSONString(loginUser));
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 放行
        filterChain.doFilter(request, response);
    }

    private void fallback(String message, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        PrintWriter writer = null;
        try {
            if (message == null) {
                message = "403 Forbidden";
            }
            R error = R.error(403, message);
            JSONObject json = new JSONObject(error);
            writer = response.getWriter();
            writer.append(json.toString());
        } catch (IOException e) {
            log.error(e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    private boolean isFilterRequest(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        String filterPath = request.getRequestURI();
        String[] filterPatterns = AppConstant.FILTER_ACCESS_PATTERNS;
        for (String path : filterPatterns) {
            String pattern = contextPath + path;
            pattern = pattern.replaceAll("/+", "/");
            if (pathMatcher.match(pattern, filterPath)) {
                return true;
            }
        }
        return false;
    }
}
